package lion.dev.text;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.apache.commons.lang.StringUtils;

/**
 * @author lion
 * @date 2011-5-26
 */
public class Formater {

	private static final String[] defaultPatterns = { "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd", "yyyy年MM月dd日 HH时mm分ss秒", "yyyy年MM月dd日" };

	private static final DecimalFormat sizeFormat = new DecimalFormat("#.##");
	private static final String currency = "###,###.00";

	public static Date parseDate(String input) {

		if (StringUtils.isBlank(input)) { return null; }

		Date result = null;
		for (String pattern : defaultPatterns) {
			DateFormat df = new SimpleDateFormat(pattern, Locale.getDefault());

			try {
				result = df.parse(input);
				break;
			} catch (ParseException e) {
				continue;
			}
		}
		return result;
	}

	public static Date parseDate(String pattern, String input) {

		if (StringUtils.isBlank(input)) { return null; }

		Date result = null;

		DateFormat df = new SimpleDateFormat(pattern, Locale.getDefault());

		try {
			result = df.parse(input);
		} catch (ParseException e) {
		}

		return result;
	}

	public static String formatDate(String pattern, Date input) {

		if (input == null) { return ""; }

		String result = "";

		DateFormat df = new SimpleDateFormat(pattern, Locale.US);

		result = df.format(input);

		return result;
	}

	public static String formatFileSize(long temp) {

		double s = temp;

		String[] format = new String[] { "{0}B", "{0}KB", "{0}MB", "{0}GB", "{0}TB", "{0}PB", "{0}EB" };

		int i = 0;
		while (i < format.length && s >= 1024) {
			s = s / 1024;
			i++;
		}

		return new MessageFormat(format[i]).format(new Object[] { sizeFormat.format(s) });
	}

	public static String formateNumber(String pattern, double number) {

		DecimalFormat df = new DecimalFormat(currency);
		if (StringUtils.isNotBlank(pattern)) {
			df.applyPattern(pattern);
		}
		return df.format(number);
	}
}
